package com.enba.boot.security.controller;

import cn.hutool.captcha.GifCaptcha;
import com.enba.boot.core.base.Result;
import com.enba.boot.redis.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "验证码")
@RestController
@RequestMapping
public class CaptchaController {

  private final RedisOperator redisOperator;

  public CaptchaController(RedisOperator redisOperator) {
    this.redisOperator = redisOperator;
  }

  @ApiOperation("获取验证码")
  @GetMapping("/captcha")
  public Result<Map<String, String>> captcha() {
    GifCaptcha gifCaptcha = new GifCaptcha(120, 35, 4, 15);

    String key = UUID.randomUUID().toString();
    String code = gifCaptcha.getCode().toLowerCase();
    redisOperator.set("captcha:" + key, code, 60);

    Map<String, String> result = new HashMap<>();
    result.put("key", key);
    result.put("image", gifCaptcha.getImageBase64Data());
    return Result.success(result);
  }
}
